<?php
/**
 * +--------------------------------------------------------------
 * | eLuoPHP
 * +--------------------------------------------------------------
 * | Copyright (c) 2016-2018 http://qxwoo.cn All rights reserved.
 * +--------------------------------------------------------------
 * | y139w [y139w@163.com]
 * +--------------------------------------------------------------
 * | CURL工具类文件
 * +--------------------------------------------------------------
 */

namespace luo\traits;


trait Curl
{

    /**
     * get方式请求页面
     * @param $url
     * @param array $header
     * @param int $time_out
     * @return mixed
     */
    public static function get($url, array $header = [], $time_out = 10){

        return self::curlRequest($url, false, [], $header, $time_out);

    }

    /**
     * post方式请求页面
     * @param $url
     * @param array $post_data
     * @param array $header
     * @param int $time_out
     * @return mixed
     */
    public static function post($url, array $post_data = [], array $header = [], $time_out = 10){

        return self::curlRequest($url, true, $post_data, $header, $time_out);

    }

    /**
     * @param $url
     * @param bool $is_post
     * @param array $params
     * @param bool $header
     * @param int $time_out
     * @return mixed
     */
    private static function curlRequest($url, $is_post = false, $params = [], $header = false, $time_out = 60){

        $ch = curl_init();//初始化curl
        // URL
        curl_setopt($ch, CURLOPT_URL, $url);
        // 设置是否返回response header
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //当需要通过curl_getinfo来获取发出请求的header信息时，该选项需要设置为true
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $time_out);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $time_out);
        curl_setopt($ch, CURLOPT_POST, $is_post);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        if (1 == strpos('$'.$url, "https://")) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        if ($is_post) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        }
        if ($header) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;

    }

}